package com.sy.simpleegg.ui.banner.manager

import android.os.Handler
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.ui.banner.ChangeBanner
import com.sy.simpleegg.ui.banner.adapter.MediaVideoBannerAdapter
import com.sy.simpleegg.ui.banner.bean.ResourceBean
import com.sy.simpleegg.ui.banner.holder.VideoHolder
import com.youth.banner.listener.OnPageChangeListener

class BannerVideoManager(
    banner: ChangeBanner<*, *>,
    adapter: MediaVideoBannerAdapter?, list: List<ResourceBean>?
) {
    private val banner: ChangeBanner<*, *>
    private val adapter: MediaVideoBannerAdapter?

    //数据源，请自行替换
    private val list: List<ResourceBean>?
    private var mPageChangeMillis: Long = 5000
    private var mVideoPlayLoadWait: Long = 500

    //设置切换间隔时间，单位毫秒
    fun setPageChangeMillis(mills: Long) {
        mPageChangeMillis = mills
    }

    /**
     * 设置视频播放前置等待时间，单位毫秒
     *
     * 设置为无限轮播时，适配器中会多出两个ViewHolder
     * 需要给banner自动切换ViewHolder一点时间
     * 保证获取到的ViewHolder是当前展示的那一个
     *
     * @param mills
     */
    fun setVideoPlayLoadWait(mills: Long) {
        mVideoPlayLoadWait = mills
    }

    /**
     * 视频+图片轮播处理代码
     */
    private var currentVideoHolder: VideoHolder? = null

    private inner class BannerPageChange : OnPageChangeListener {
        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
        }

        override fun onPageSelected(position: Int) {
            mPosition = position
            if (adapter != null) {
                currentVideoHolder = null
                //当前页不是视频类型
                if (list!![position].type != 2) {
                    adapter.stopVideo()
                    if (videoPlayRunnable != null) mHandler.removeCallbacks(videoPlayRunnable!!)
                    startScroll(mPageChangeMillis)
                } else {
                    //视频类型，且仅有一个视频，自动重播
                    if (list.size == 1) playVideo(0, position) else {
                        playVideo(mVideoPlayLoadWait, position + 1)
                    }
                    stopScroll()
                }
            }
        }

        override fun onPageScrollStateChanged(state: Int) {}
    }

    //当前position（显示出来的position，非真实position
    private var mPosition = 0
    private val mHandler = Handler()

    //轮播切换的runnable
    private val runnable: Runnable = object : Runnable {
        override fun run() {
            mHandler.removeCallbacks(this)
            banner.setCurrentItem(banner.currentItem + 1, true)
        }
    }

    //控制视频播放
    private var videoPlayRunnable: Runnable? = null

    init {
        GSYVideoType.setShowType(GSYVideoType.SCREEN_MATCH_FULL)
        this.banner = banner
        this.adapter = adapter
        this.list = list
        banner.addOnPageChangeListener(BannerPageChange())
    }

    private fun playVideo(millis: Long, position: Int) {
        try {
            if (videoPlayRunnable != null) mHandler.removeCallbacks(videoPlayRunnable!!)
            videoPlayRunnable = Runnable {
                if (position == 1 && list!!.size > 1 && banner.currentItem != 1) {
                    banner.setCurrentItem(1, false)
                    return@Runnable
                }
                val videoHolder = adapter!!.getVideoHolder(position)
                if (videoHolder == null) {
                    showToast("获取视频播放控件出错")
                    return@Runnable
                }
                videoHolder.player.onVideoReset()
                videoHolder.player.startPlayLogic()
                videoHolder.player.setVideoAllCallBack(object : GSYSampleCallBack() {
                    override fun onAutoComplete(url: String, vararg objects: Any) {
                        super.onAutoComplete(url, *objects)
                        if (position == 0) videoHolder.player.startPlayLogic() else startScroll(0)
                    }
                })
                currentVideoHolder = videoHolder
            }
            mHandler.postDelayed(videoPlayRunnable!!, millis)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("${javaClass.simpleName}playVideo异常：${e.message}")
        }
    }

    //停止轮播，并等待切换数据源
    fun stopBeforeChangeResource() {
        onPause()
        currentVideoHolder = null
    }

    //切换数据源，并开始轮播
    fun startAlterChangeResource() {
        banner.setCurrentItem(1, false)
        mPosition = 0
        banner.indicator!!.onPageSelected(mPosition)
        onResume()
    }

    //开始切换
    private fun startScroll(millis: Long) {
        mHandler.postDelayed(runnable, millis)
    }

    //停止切换
    private fun stopScroll() {
        mHandler.removeCallbacks(runnable)
    }

    private fun showToast(str: String) {
        showToastMsg(str)
    }

    //Activity生命周期控制
    fun onPause() {
        try {
            stopScroll()
            if (currentVideoHolder != null) currentVideoHolder!!.player.onVideoPause()
            mHandler.removeCallbacks(videoPlayRunnable!!)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("${javaClass.simpleName}onPause异常：${e.message}")
        }
    }

    //Activity生命周期控制
    fun onResume() {
        try {
            if (list == null) return
            if (list.size == 0) return
            if (list[mPosition].type == 2) {
                if (currentVideoHolder != null) currentVideoHolder!!.player.onVideoResume() else {
                    if (list.size == 1) playVideo(mVideoPlayLoadWait, mPosition) else playVideo(
                        mVideoPlayLoadWait,
                        mPosition + 1
                    )
                }
            } else {
                if (list.size == 1) banner.setCurrentItem(mPosition, false) else banner.setCurrentItem(
                    mPosition + 1,
                    false
                )
                //banner.getIndicator().onPageSelected(mPosition);
                startScroll(mPageChangeMillis)
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("${javaClass.simpleName}onResume异常：${e.message}")
        }
    }

    //Activity生命周期控制
    fun onDetachedFromWindow() {
        stopScroll()
    }
}
